package com.atguigu.security.filter;

import com.alibaba.fastjson2.JSON;
import com.atguigu.common.jwt.JwtHelper;
import com.atguigu.common.result.ResponseUtil;
import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.security.custom.LoginUserInfoHelper;
import lombok.val;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * className: TokenAuthenticationFilter
 * description: 认证解析token过滤器
 * date: 2023/4/17 0017-23:05
 * <p>
 * project: guigu-oa-parent
 * package: com.atguigu.security.filter
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private static final String LOGIN_URL = "/admin/system/index/login";

    private final RedisTemplate<String, String> redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * token 过滤器
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @param chain    {@link FilterChain}
     * @throws ServletException {@link ServletException} e
     * @throws IOException      {@link IOException}  e
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws ServletException, IOException {
        // 如果是登录接口，直接放行
        if (LOGIN_URL.equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.LOGIN_ERROR));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token 置于 header
        String token = request.getHeader("token");
        logger.info("token: " + token);
        if (!StringUtils.isEmpty(token)) {
            String username = JwtHelper.getUsername(token);
            logger.info("username: " + username);
            if (!StringUtils.isEmpty(username)) {
                // 当前用户信息放入到 ThreadLocal
                LoginUserInfoHelper.setUserId(JwtHelper.getUserId(token));
                LoginUserInfoHelper.setUsername(JwtHelper.getUsername(token));

                // 通过 username 从 redis 获取 权限数据
                String authString = redisTemplate.opsForValue().get(username);
                // 把 redis 获取的字符串权限数据转换要求集合类型 List<SimpleGrantedAuthority>
                if (!StringUtils.isEmpty(authString)) {
                    val mapList = JSON.parseArray(authString, Map.class);
                    List<SimpleGrantedAuthority> authList = new ArrayList<>();
                    for (val map : mapList) {
                        String authority = (String) map.get("authority");
                        authList.add(new SimpleGrantedAuthority(authority));
                    }
                    return new UsernamePasswordAuthenticationToken(username, null, authList);
                }
                return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            }
        }
        return null;
    }

}
